package com.sky.mapper;

import com.github.pagehelper.Page;
import com.sky.dto.OrdersConfirmDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.entity.Orders;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Mapper
public interface OrderMapper {

    /**
     * 订单表插入一条数据
     * @param orders
     */
    void insert(Orders orders);

    /**
     * 修改订单状态
     * @param order
     */
    @Update("update orders set status = #{status}, pay_status = #{payStatus}, " +
            "checkout_time = #{checkoutTime}, rejection_reason = #{rejectionReason}, cancel_reason = #{cancelReason}, cancel_time = #{cancelTime} where number = #{number}")
    void changeStatus(Orders order);

    /**
     * 获取历史订单
     * @param ordersPageQueryDTO
     * @return
     */
    Page<Orders> getHistoryOrders(OrdersPageQueryDTO ordersPageQueryDTO);

    /**
     * 根据订单id查询订单
     * @param id
     * @return
     */
    @Select("select * from orders where id = #{id}")
    Orders getById(Long id);

    /**
     * 统计订单数量
     *
     * @param toBeConfirmed
     * @return
     */
    @Select("select count(*) from orders where status = #{toBeConfirmed}")
    Integer countStatus(Integer toBeConfirmed);

    /**
     * 修改订单状态
     * @param ordersConfirmDTO
     */
    @Update("update orders set status = #{status} where id = #{id}")
    void setStatus(OrdersConfirmDTO ordersConfirmDTO);

    /**
     * 根据订单状态和下单时间查询订单
     */
    @Select("select * from orders where status = #{status} and order_time < #{time}")
    List<Orders> getOverOrderTime(Integer status, LocalDateTime time);

    /**
     * 根据订单号查ID
     * @param orderNumber
     * @return
     */
    @Select("select id from orders where number = #{orderNumber}")
    Long getByNumber(String orderNumber);

    /**
     * 查询订单金额总和, 并且状态为已完成
     *
     * @param date
     */
    @Select("select sum(amount) from orders where date_format(order_time, '%Y-%m-%d') = #{date} and status = 5")
    BigDecimal selectOrderAmountSum(LocalDate date);

    /**
     * 查询用户总量
     * 查询consignee字段,去重,计算数量
     * @param date
     */
    @Select("select count(distinct consignee) from orders where date_format(order_time, '%Y-%m-%d') = #{date}")
    String selectUserCount(LocalDate date);

    /**
     * 查询当天的订单数量
     */
    @Select("select count(*) from orders where date_format(order_time, '%Y-%m-%d') = #{date}")
    Integer countAll(LocalDate date);

    /**
     * 查询当天的有效订单数量
     * @param i
     * @param date
     * @return
     */
    @Select("select count(*) from orders where status = #{i} and date_format(order_time, '%Y-%m-%d') = #{date}")
    Integer countVaildStatus(int i, LocalDate date);

    Double sumByMap(Map map);
    Integer countByMap(Map map);


}
